package com.train.mgr.modules.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.common.enums.PublishEnum;
import com.train.common.exception.BizException;
import com.train.common.model.PageResult;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.DateUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.modules.biz.dto.request.CourseQueryReqDTO;
import com.train.mgr.modules.biz.dto.request.CourseReqDTO;
import com.train.mgr.modules.biz.dto.response.CourseRespDetailDTO;
import com.train.mgr.modules.biz.dto.response.CourseRespListDTO;
import com.train.mgr.modules.biz.dto.response.TraineeStuRespDTO;
import com.train.mgr.modules.biz.entity.Course;
import com.train.mgr.modules.biz.entity.CourseUser;
import com.train.mgr.modules.biz.entity.Customer;
import com.train.mgr.modules.biz.entity.LessonUserStudy;
import com.train.mgr.modules.biz.mapper.CourseMapper;
import com.train.mgr.modules.biz.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author cxg
 * @date 2025-09-30
 */
@Slf4j
@RequiredArgsConstructor
@Service("ICourseService")
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    private final CustomerService customerService;

    private final ICourseUserService courseUserService;

    private final ILessonUserStudyService lessonUserStudyService;

    private final ILessonService lessonService;

    @Override
    public CourseRespDetailDTO findDetailById(Long courseId){
        Course bean = this.getById(courseId);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        CourseRespDetailDTO dto = BeanUtil.copyProperties(bean, CourseRespDetailDTO.class);
        if(bean.getDeadline() != null){
            dto.setDeadline(DateUtils.parseDateToStr(bean.getDeadline()));
        }

        LambdaQueryWrapper<CourseUser> queryLessonWrapper = new LambdaQueryWrapper<CourseUser>();
        queryLessonWrapper.eq(CourseUser::getCourseId,courseId);
        queryLessonWrapper.eq(CourseUser::getIsDeleted,0);
        List<CourseUser> courseUserList = courseUserService.list(queryLessonWrapper);
        if(ObjectUtil.isNotEmpty(courseUserList)){
            Long hasFinishedCount = courseUserList.stream()
                    .filter(cu -> cu.getIsFinish() != null && cu.getIsFinish() == 1)
                    .count();
            dto.setHasFinishStuNum(Integer.parseInt(hasFinishedCount.toString()));
            dto.setStudentNum(courseUserList.size());
        }
        return dto;
    }

    @Transactional
    @Override
    public Long save(CourseReqDTO dto){
        this.checkByCourseName(dto.getCourseName(),null);
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        String companyCode = "";
        Customer custBean = customerService.getById(customerId);
        if(ObjectUtil.isNotEmpty(custBean)){
            companyCode = custBean.getCompanyCode();
        }
        if(StringUtils.isEmpty(companyCode)){
            throw new BizException("企业码为空，请先配置～");
        }

        String currentCount = this.getTodayCourseCount(customerId);
        String courseCode = companyCode + DateUtils.getYMDDate() +currentCount ;
        Course bean = new Course();
        bean.setCustomerId(customerId);
        bean.setCourseName(dto.getCourseName());
        bean.setCourseCode(courseCode);
        bean.setCreateBy(AuthUtils.getCurrentUser().getNickName());
        baseMapper.insert(bean);
        return bean.getId();
    }

    @Transactional
    @Override
    public boolean update(CourseReqDTO dto){
        this.checkByCourseName(dto.getCourseName(),dto.getId());
        Course bean = this.getById(dto.getId());
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        bean.setCourseName(dto.getCourseName());
        bean.setCourseIntroduction(dto.getCourseIntroduction());
        if(StringUtils.isNotEmpty(dto.getDeadline())){
            bean.setDeadline(DateUtils.toDate(dto.getDeadline()));
            bean.setIsLimitTime(1);//1
        }else{
            bean.setDeadline(null);
            bean.setIsLimitTime(0);//1
        }
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Transactional
    @Override
    public boolean deleteById(Long id){
        //查询是否存在学员学习数据
        LambdaQueryWrapper<LessonUserStudy> queryLessonWrapper = new LambdaQueryWrapper<LessonUserStudy>();
        queryLessonWrapper.eq(LessonUserStudy::getCourseId,id);
        queryLessonWrapper.eq(LessonUserStudy::getIsDeleted,0);
        long count = lessonUserStudyService.count(queryLessonWrapper);
        if(count >0){
            throw new BizException("该课程已有学习数据，不可删除！");
        }
        int result = baseMapper.deleteById(id);
        if(result >0){
            //删除课时数据
            lessonService.delByCoursId(id);

            //删除学员数据
            courseUserService.delByCoursId(id);
        }
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public boolean publish(Long id){
        Course bean = this.getById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        if(PublishEnum.HAS_PUBLIC.getCode().equals(bean.getIsPublish())){
            throw new BizException("不可重复发布～");
        }
        bean.setIsPublish(PublishEnum.HAS_PUBLIC.getCode());
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public boolean unPublish(Long id){
        Course bean = this.getById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        if(PublishEnum.UN_PUBLIC.equals(bean.getIsPublish())){
            throw new BizException("不可重复取消发布～");
        }
        bean.setIsPublish(0);
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public boolean selfGroup(Long id, Long status){
        Course bean = this.getById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        if (status == null || ( 0!=status && 1!=status)) {
            throw new BizException("status参数不正确");
        }

        bean.setIsSelfGroup(Integer.parseInt(status.toString()));
        bean.setUpdateBy(AuthUtils.getNickname());
        bean.setUpdateTime(new Date());
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public boolean checkReview(Long id, Long isReview){
        Course bean = this.getById(id);
        if(ObjectUtil.isEmpty(bean)){
            throw new BizException("课程记录为空");
        }
        if (isReview == null || ( 0!=isReview && 1!=isReview)) {
            throw new BizException("isReview参数不正确");
        }
        bean.setReviewState(Integer.parseInt(isReview.toString()));
        bean.setUpdateBy(AuthUtils.getNickname());
        bean.setUpdateTime(new Date());
        int result = baseMapper.updateById(bean);
        boolean bool = result >0 ? true : false;
        return bool;
    }

    @Override
    public PageResult<CourseRespListDTO> pageList(CourseQueryReqDTO params){
        params.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        Page<CourseRespListDTO> page = params.buildPage();
        Page<CourseRespListDTO> resultPage = baseMapper.selectList(page,params);
        for(CourseRespListDTO courseBean : resultPage.getRecords()){
            long courseId = courseBean.getId();
            LambdaQueryWrapper<CourseUser> queryLessonWrapper = new LambdaQueryWrapper<CourseUser>();
            queryLessonWrapper.eq(CourseUser::getCourseId,courseId);
            queryLessonWrapper.eq(CourseUser::getIsDeleted,0);
            List<CourseUser> courseUserList = courseUserService.list(queryLessonWrapper);
            if(ObjectUtil.isNotEmpty(courseUserList)){
                long hasFinishedCount = courseUserList.stream()
                        .filter(cu -> cu.getIsFinish() != null && cu.getIsFinish() == 1)
                        .count();
                courseBean.setHasFinishStuNum(hasFinishedCount);
                courseBean.setStudentNum(courseUserList.size());
            }
        }
        return PageResult.of(resultPage, CourseRespListDTO.class);
    }

    @Override
    public Course selectCourceByCourceCode(String courceCode, Long customerId) {
        return baseMapper.selectCourceByCourceCode(courceCode, customerId);
    }

    @Override
    public TraineeStuRespDTO getStuCourseCount() {
        return baseMapper.getStuCourseCount(AuthUtils.getCurrentUser().getId());
    }

    @Override
    public List<Course> getCourseList() {
        return baseMapper.getCourseList();
    }

    private String getTodayCourseCount(long customerId){
        String todayDate = DateUtils.getDate();
        LambdaQueryWrapper<Course> wrapper = Wrappers.<Course>lambdaQuery()
                .eq(Course::getCustomerId, customerId)
                .likeRight(Course::getCreateTime, todayDate)
                .eq(Course::getIsDeleted, 0);
        long count = baseMapper.selectCount(wrapper) + 1;   // 空表也先+1
        return String.format("%02d", count);
    }

    private void checkByCourseName(String courseName,Long id ) {
        if (StrUtil.isEmpty(courseName)) {
            throw new BizException("课程名称不能为空");
        }
//        LambdaQueryWrapper<Course> wrapper = Wrappers.<Course>lambdaQuery()
//                .eq(Course::getCourseName, courseName)
//                .ne(id != null && id > 0, Course::getId, id) // 如果是编辑，则排除自己
//                .eq(Course::getIsDeleted, 0);
//        Long result = baseMapper.selectCount(wrapper);
//        if(result >0){
//            throw new BizException("课程名称重复，请重新输入");
//        }
    }

}
